//
//  ViewController.swift
//  testAlamofire
//
//  Created by 金善成 on 2020/12/21.
//  Copyright © 2020 cc. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON
import SwiftyJSON

class ViewController: UIViewController, URLSessionDownloadDelegate {

    let path = "https://imgtest.jobpoolhr.com/api/helpType/list?type=employment"
    override func viewDidLoad() {
        super.viewDidLoad()
//        abcBlock()
        semaphore()
    }
    
    func abcBlock(){
        let semaphoreA = DispatchSemaphore(value: 1)
        let semaphoreB = DispatchSemaphore(value: 1)
        let semaphoreC = DispatchSemaphore(value: 1)
        
//        let queueA = DispatchQueue(label: "queuea", qos: ., attributes: .concurrent, autoreleaseFrequency: <#T##DispatchQueue.AutoreleaseFrequency#>, target: <#T##DispatchQueue?#>)
        
        DispatchQueue.main.async(execute: DispatchWorkItem{print("")})
//        NSLock *lockA = [[NSLock alloc] init];
//        NSLock *lockB = [[NSLock alloc] init];
//        NSLock *lockC = [[NSLock alloc] init];
//
//        [lockB lock];
//        [lockC lock];
//
//        dispatch_queue_t queueA = dispatch_queue_create("queuea", DISPATCH_QUEUE_CONCURRENT);
//        dispatch_async(queueA, ^{
//            for (int i = 0; i<10; i++) {
//                [lockA lock];
//                NSLog(@"A======= %@",@(i));
//                [lockB unlock];
//            }
//        });
//
//        dispatch_queue_t queueB = dispatch_queue_create("queueb", DISPATCH_QUEUE_CONCURRENT);
//        dispatch_async(queueB, ^{
//            for (int i = 0; i<10; i++) {
//                [lockB lock];
//                 NSLog(@"B======= %@",@(i));
//                [lockC unlock];
//            }
//        });
//
//        dispatch_queue_t queueC = dispatch_queue_create("queuec", DISPATCH_QUEUE_CONCURRENT);
//        dispatch_async(queueC, ^{
//            for (int i = 0; i<10; i++) {
//                [lockC lock];
//                 NSLog(@"C======= %@",@(i));
//                 NSLog(@"   ");
//                [lockA unlock];
//            }
//        });
    }
    
    func dispatchItem(){
        let _ = DispatchWorkItem.init(qos: .userInteractive, flags: .barrier) {
            print("2222")
        }
    }
    
    func alamofireRequest() {
//        AF.request(path, method: .get, parameters: [:], headers: HTTPHeaders.init(["Content-Type":"application/json","Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzg4MDI3NjE5NyIsImNyZWF0ZWQiOjE2MDgyNzAzMTMxNzUsImV4cCI6MTYxMzQ1NDMxM30.n7llFBJaaeIW1wsOPlmBf7kNkS9fGaCVAZSVQYZ2GxDFyiWCkHAozKfMbl0Q6moqTRaoZer-Tz2A4Uk-qp5D_w"])).response { (data) in
//            do{
//                let json = try JSONSerialization.jsonObject(with: data.data!, options: .allowFragments)
////                print(json)
//            } catch {
//
//            }
//        }
        
//        AF.request(path, method: .get, parameters: [:], headers: HTTPHeaders.init(["Content-Type":"application/json","Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzg4MDI3NjE5NyIsImNyZWF0ZWQiOjE2MDgyNzAzMTMxNzUsImV4cCI6MTYxMzQ1NDMxM30.n7llFBJaaeIW1wsOPlmBf7kNkS9fGaCVAZSVQYZ2GxDFyiWCkHAozKfMbl0Q6moqTRaoZer-Tz2A4Uk-qp5D_w"])).responseData { (data) in
//            do{
//                            let json = try JSONSerialization.jsonObject(with: data.data!, options: .allowFragments)
//                            print(json)
//                        } catch {
//
//                        }
//
        
        
        
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 30
        config.httpAdditionalHeaders = [:]
        config.allowsCellularAccess = true
        let session =  Alamofire.Session(configuration:config)
        session.request(path, method: .get, parameters: [:], headers: HTTPHeaders.init(["Content-Type":"application/json","Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzg4MDI3NjE5NyIsImNyZWF0ZWQiOjE2MDgyNzAzMTMxNzUsImV4cCI6MTYxMzQ1NDMxM30.n7llFBJaaeIW1wsOPlmBf7kNkS9fGaCVAZSVQYZ2GxDFyiWCkHAozKfMbl0Q6moqTRaoZer-Tz2A4Uk-qp5D_w"])).responseJSON { (data) in
            print("测试测试")
            switch data.result {
            case .success(let json):
                print(json)
                break
            case .failure(let error):
                print(error.localizedDescription)
                break
            }
        }
    }
    
    func uploadData() {
        let picurl = ""
        guard let picrequest = URL(string: picurl) else {
            return
        }
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
        session.uploadTask(with: URLRequest(url: picrequest), from: Data()) { (data, _, _) in
            print(data ?? "")
        }.resume()
    }
    
    
    //下载图片
    func downloadPicUrl(){
        let picurl = "https://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fwww.s5themes.com%252Fwp-content%252Fuploads%252F2012%252F07%252Fdreamland_small.jpg%26refer%3Dhttp%253A%252F%252Fwww.s5themes.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1611392928%26t%3D92c6b6f10960f42db598d6cca197b1e4&thumburl=https%3A%2F%2Fss2.bdstatic.com%2F70cFvnSh_Q1YnxGkpoWK1HF6hhy%2Fit%2Fu%3D1109696316%2C2841043784%26fm%3D15%26gp%3D0.jpg"
        guard let picrequest = URL(string: picurl) else {
            return
        }
        do {
            let data = try Data.init(contentsOf: picrequest)
            guard let image = UIImage(data: data) else {
                return
            }
            //寸照片到相册
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSaving:contextInfo:)), nil)
        } catch {
            
        }
        
        return
        //下载文件
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
        let downloadTask = session.downloadTask(with: URLRequest(url: picrequest)) { (url, _, error) in
            print(url ?? "")
            print("error:\(String(describing: error))")
        }
        downloadTask.resume()
        
        //取消
        downloadTask.cancel { (data) in
            
        }
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("location:\(location)")
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print("didWriteData:\(bytesWritten),  totalBytesWritten:\(totalBytesWritten),    totalBytesExpectedToWrite:\(totalBytesExpectedToWrite),     percent:\(bytesWritten/totalBytesWritten)%")
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        print("fileOffset:\(fileOffset)")
    }
    
    @objc func image(image:UIImage, didFinishSaving:NSError?, contextInfo:AnyObject?) {
        if didFinishSaving != nil {
            print("保存错误")
        } else {
            print("成功")
        }
    }
    
    
    
    
    
    
    //urlsession网络请求
    func request(){
        guard let url = URL(string: path) else {
            return
        }
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 30
        config.allowsCellularAccess = true
        config.httpAdditionalHeaders = ["Content-Type":"application/json","Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzg4MDI3NjE5NyIsImNyZWF0ZWQiOjE2MDgyNzAzMTMxNzUsImV4cCI6MTYxMzQ1NDMxM30.n7llFBJaaeIW1wsOPlmBf7kNkS9fGaCVAZSVQYZ2GxDFyiWCkHAozKfMbl0Q6moqTRaoZer-Tz2A4Uk-qp5D_w"]
        var requet = URLRequest.init(url: url)
        if let charretUrl = URL(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {
            requet.url = charretUrl
        }
        requet.httpMethod = "GET"
        requet.timeoutInterval = 30
//        requet.httpBody = "type=employment".data(using: .utf8)
//        requet.allHTTPHeaderFields = ["Content-Type":"application/json","Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzg4MDI3NjE5NyIsImNyZWF0ZWQiOjE2MDgyNzAzMTMxNzUsImV4cCI6MTYxMzQ1NDMxM30.n7llFBJaaeIW1wsOPlmBf7kNkS9fGaCVAZSVQYZ2GxDFyiWCkHAozKfMbl0Q6moqTRaoZer-Tz2A4Uk-qp5D_w"]
        let session = URLSession(configuration: config)
//        session = URLSession.shared
        session.dataTask(with: requet) { (data, _, _) in
            print(Thread.current)
            if let result = data {
                let json = JSONDeserializer<model>.deserializeFrom(json: JSON(result).description)
                do {
//                    let json = try JSONSerialization.jsonObject(with: result, options: .allowFragments)
//                    if let dic = json as? [AnyHashable:Any] {
//                        for item in dic {
//                            print("字典:\(item.value)")
//                        }
//                        print(dic)
//                    }
                } catch {
                    
                }
                
            }
        }.resume()

    }
    
    //信号量DispatchSemaphore
    func semaphore(){
        let queue = DispatchQueue.global()//DispatchQueue(label: "自我设置", qos: DispatchQoS.default, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil)//DispatchQueue.global()
        let group = DispatchGroup()
        let semaphore = DispatchSemaphore(value: 1)
        
        for idx in 0...9 {
            queue.async(group: group) {
                semaphore.wait()
                self.semaphoreTask(currentIdx:"1" ,label: String(idx), cost: 2, complete: {
//                    print(Thread.current)
                    semaphore.signal()
                })
            }
            queue.async(group: group) {
                semaphore.wait()
                self.semaphoreTask(currentIdx:"2" ,label: String(idx), cost: 2, complete: {
//                    print(Thread.current)
                    semaphore.signal()
                })
            }
            queue.async(group: group) {
                semaphore.wait()
                self.semaphoreTask(currentIdx:"3" ,label: String(idx), cost: 2, complete: {
//                    print(Thread.current)
                    semaphore.signal()
                })
            }
        }

            group.notify(queue: queue) {
                print("All task has finished:\(Thread.current)")
            }

        DispatchQueue.main.async {
            print("main_1:\(Thread.current)")
        }

        print(Thread.current)
    }
    
    public func semaphoreTask(currentIdx:String,label:String, cost:UInt32, complete:@escaping ()->()){
        print("\(currentIdx) ***** Start semaphore task \(label)")
//        sleep(4)
        print("\(currentIdx) ***** End semaphore task  \(label)")
        print(complete())
    }


}

